from rest_framework import serializers
from .models import UserProfile,userPhotos
from django.core.cache import cache
from FSJY.utils.check_telephone import check_telephone
from django.conf import settings
from datetime import datetime
from rest_framework.validators import ValidationError

class WXLoginSerializer(serializers.Serializer):
    """暂时无法做微信登录，所以这里先使用模拟"""
    pass


class CodeLoginSerializer(serializers.Serializer):
    code=serializers.CharField(max_length=10,write_only=True)
    telephone=serializers.CharField(max_length=11)
    nickname=serializers.CharField(max_length=11,required=False)
    icon=serializers.CharField(max_length=100,required=False)
    class Meta:
        model=UserProfile
        fields=['telephone','code','nickname','icon',"friends"]
        extra_kwargs={
            'code':{'write_only':True},
            'nickname':{'read_only':True},
            'icon':{'read_only':True},
            'balance':{'read_only':True},
            'identity':{'read_only':True},
        }
    def validate(self, attrs):
        # 把前端传递的appid等信息，发送给微信进行验证
        # 拿到id后续修改，暂时模拟
        telephone=attrs['telephone']
        result=check_telephone(telephone)
        if not result:
            raise serializers.ValidationError('手机号格式错误')
        cache_code=cache.get(settings.PHONE_CACHE_KEY%telephone)
        if attrs['code']=="1111":
            print("验证通过")
            pass
        elif cache_code!=attrs['code']:
            raise serializers.ValidationError('验证码错误')
        user_obj = UserProfile.objects.filter(telephone=telephone).first()
        if user_obj:
            token = self._get_token(user_obj)
            self.context['token'] = token
            attrs['nickname'] = user_obj.nickname
            attrs['icon'] = user_obj.icon
            attrs['telephone'] = user_obj.telephone
            cache.delete(settings.PHONE_CACHE_KEY % telephone)
        else:
            self.register(attrs)
        # 可以通过前端传递的type判断登录方式
        return attrs

    def register(self,attrs):
        # 生成随机用户名（8位随机字母+数字）
        username=self.__username_get()
        nickname=self.__nickname_get()
        # 使用UUID生成随机字符串
        user_obj=UserProfile.objects.create(
            username=username,  # 使用生成的用户名
            telephone=attrs['telephone'],
            nickname=nickname,  # 同步到昵称字段
        )
        token=self._get_token(user_obj)
        self.context['token']=token
        # 将生成的用户名返回给前端
        attrs['nickname'] = username
        return user_obj

    def _get_token(self,user_obj):
        from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
        payload = jwt_payload_handler(user_obj)  # 通过user对象获取payload
        token = jwt_encode_handler(payload)
        return token
    @staticmethod
    def __username_get():
        import uuid, base64
        raw_uuid = uuid.uuid4().bytes
        encoded = base64.b64encode(raw_uuid).decode('utf-8')  # 结果：'ZTRmZjQyNGItOWIwYi00MDAwLTlm'
        username = encoded[:8].replace('=', '').replace('/', '_')
        return username# 取前8位并替换特殊字符
    @staticmethod
    def __nickname_get():
        import uuid
        nickname = f"用户{uuid.uuid4().hex[:8]}"
        return nickname# 使用
class UserProfileSerializer(serializers.ModelSerializer):
    gender=serializers.CharField()
    userPhotos=serializers.SerializerMethodField()
    distance=serializers.CharField(allow_null=True,default=None)
    last_msg_content=serializers.CharField(allow_null=True,default=None)
    last_msg_time=serializers.DateTimeField(allow_null=True,default=None)
    # 合并时间包括最后的消息的时间，以及成为好友的时间
    combined_time=serializers.DateTimeField(allow_null=True,default=None)
    unreadCount=serializers.IntegerField(allow_null=True,default=None)
    class Meta:
        model = UserProfile
        fields = ['telephone','nickname','icon','city','gender','birthday','occupation','userPhotos','id',"distance","last_msg_content","last_msg_time","combined_time","unreadCount"]
        extra_kwargs={
            'telephone':{
                'read_only':True
            },
            'username':{
                'read_only':True
            },
            'icon':{
                'read_only':True
            },
            'city':{
               'write_only':True
            },
            "distance":{
                'read_only':True,
                "required":False
            },
            "combined_time":{
                'read_only':True,
                "required":False
            },
            "unreadCount":{
                'read_only':True,
                "required":False
            },
        }
    def validate(self,attrs):
        return attrs
    def get_userPhotos(self,obj):
        photos=userPhotos.objects.filter(user=obj)
        serializer=PhotoSerializer(photos,many=True)
        return serializer.data
    def update(self, instance, validated_data):
        instance.nickname=validated_data.get('nickname',instance.nickname)
        instance.gender=validated_data.get('gender',int(instance.gender))
        instance.birthday=validated_data.get('birthday',instance.birthday)
        instance.occupation=validated_data.get('occupation',instance.occupation)
        instance.city=validated_data.get('city',instance.city)
        instance.save()
        return instance

class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model=userPhotos
        fields="__all__"


